package com.hmall.controller.back;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.hdmall.business.common.annotation.AuthRequired;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hdmall.business.common.util.ReadExcel;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.service.*;
import com.hmall.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpDirEntry;
import sun.net.ftp.FtpProtocolException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.*;

@RestController
@RequestMapping("/manage/product")
@Api(value = "后台产品管理操作API", description = "后台产品管理类API说明")
public class ProductManageController {

    private final ProductService iProductService;
    private final MallAttrConnectService mallAttrConnectService;
    private final MallPriceService mallPriceService;
    private final MallAttrMapper mallAttrMapper;
    private final MallAttrValueMapper mallAttrValueMapper;
    private final MallProductMapper mallProductMapper;
    private final MallPriceMapper mallPriceMapper;
    private final MallAttrConnectMapper mallAttrConnectMapper;
    private final MallHotMapper mallHotMapper;
    private final MallProductInStorageMapper mallProductInStorageMapper;
    private final SysCustomerDetailMapper sysCustomerDetailMapper;
    private final SysDeptMapper sysDeptMapper;
    private final SysCustomerMapper sysCustomerMapper;
    private final SysDeptCustomerMapper sysDeptCustomerMapper;
    private final MallProductForwardStockMapper mallProductForwardStockMapper;
    private final MallOrderItemDetailMapper mallOrderItemDetailMapper;
    private final MallProductPriceMapper mallProductPriceMapper;
    private final MallOrderItemMapper mallOrderItemMapper;
    private final NcOutStockMapper ncOutStockMapper;
    private final MallOrderMapper mallOrderMapper;

    @Autowired
    public ProductManageController(MallAttrConnectService mallAttrConnectService, UserService iUserService, ProductService iProductService, FileService iFileService, MallProductPriceMapper mallProductPriceMapper, NcOutStockMapper ncOutStockMapper, MallProductInStorageMapper mallProductInStorageMapper, MallPriceService mallPriceService, MallAttrMapper mallAttrMapper, MallProductStockMapper mallProductStockMapper, SysDeptCustomerMapper sysDeptCustomerMapper, MallOrderItemDetailMapper mallOrderItemDetailMapper, MallAttrValueMapper mallAttrValueMapper, MallProductMapper mallProductMapper, SysDeptMapper sysDeptMapper, MallPriceMapper mallPriceMapper, MallOrderItemMapper mallOrderItemMapper, SysCustomerMapper sysCustomerMapper, MallProductForwardStockMapper mallProductForwardStockMapper, MallAttrConnectMapper mallAttrConnectMapper, SysCustomerDetailMapper sysCustomerDetailMapper, MallOrderMapper mallOrderMapper, MallHotMapper mallHotMapper) {
        this.mallAttrConnectService = mallAttrConnectService;
        this.iProductService = iProductService;
        this.mallProductPriceMapper = mallProductPriceMapper;
        this.ncOutStockMapper = ncOutStockMapper;
        this.mallProductInStorageMapper = mallProductInStorageMapper;
        this.mallPriceService = mallPriceService;
        this.mallAttrMapper = mallAttrMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.mallOrderItemDetailMapper = mallOrderItemDetailMapper;
        this.mallAttrValueMapper = mallAttrValueMapper;
        this.mallProductMapper = mallProductMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.sysCustomerMapper = sysCustomerMapper;
        this.mallProductForwardStockMapper = mallProductForwardStockMapper;
        this.mallAttrConnectMapper = mallAttrConnectMapper;
        this.sysCustomerDetailMapper = sysCustomerDetailMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.mallHotMapper = mallHotMapper;
    }

    @GetMapping("wms")
    @ApiOperation(value = "wms")
    public ServerResponse wms() {
        List<MallProductForwardStock> list = mallProductForwardStockMapper.selectAll();
        Map map = new HashMap();
        for (MallProductForwardStock mallProductForwardStock : list) {
            map.put("itemBarCode", mallProductForwardStock.getId().toString());
            map.put("itemName", mallProductForwardStock.getMaterialCode());
            map.put("itemClass", mallProductForwardStock.getGrade() + "-" + mallProductForwardStock.getTwisting() + "-" + mallProductForwardStock.getColor() + "-" + mallProductForwardStock.getMachineNo());
            map.put("upperLimit", "100000");
            map.put("floorLimit", "1000");
            map.put("memo", mallProductForwardStock.getMaterialName());
            HttpClientUtil.doGetWithParam("http://localhost:9600/wms/item/infos/test", map);
        }
        return ServerResponse.createBySuccess("结束");
    }

    @AuthRequired
    @PostMapping("CreatedProduct")
    @ApiOperation(value = "添加产品")
    public ServerResponse<Integer> add(@RequestBody BProductVo productVo, HttpServletRequest request) {
        //判断是否存在这种产品
        System.out.println("新建产品:" + productVo.toString());
        int count = mallAttrConnectService.checkModel(productVo.getModel());
        System.out.println(count);
        if (count != 0) {
            int productId = mallAttrConnectService.findProductIdByModel(productVo.getModel());
            return ServerResponse.createBySuccess("重复产品", productId);
        }
        System.out.println("新建产品:" + productVo.toString());
        String name = CreateOrUpdateProduct(productVo, true);
        Integer product_id = iProductService.findByProductName(name);
        updateProductPriceRange(product_id, productVo);
        CreateOrUpdateAttrConnect(product_id, productVo);
        //return ServerResponse.createBySuccess("创建成功");
        return ServerResponse.createBySuccess(name, product_id);
    }

    @AuthRequired
    @PostMapping("GetProductList")
    @ApiOperation(value = "获取产品列表")
    public ServerResponse<PageInfo<MallProduct>> GetProductList(Integer dept_id, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                                @RequestParam(value = "pageSize", defaultValue = "100") int pageSize) {
        return iProductService.getProductList2(dept_id, pageNum, pageSize);
    }

    @AuthRequired
    @DeleteMapping("DeleteProduct")
    @ApiOperation(value = "删除产品")
    public ServerResponse DeleteProduct(Integer[] id) {
        int product_id;
        int count = 0;
        for (Integer anId : id) {
            product_id = anId;
            count = count + mallProductMapper.deleteByPrimaryKey(product_id);
        }
        if (count == 0) {
            return ServerResponse.createByErrorMessage("删除失败");
        } else {
            return ServerResponse.createBySuccess("删除成功");
        }
    }

    @AuthRequired
    @PostMapping("EditProduct")
    @ApiOperation(value = "修改产品")
    public ServerResponse<Integer> EditProduct(@RequestBody BProductVo productVo) {

        System.out.println("更新产品:" + productVo.toString());

        Integer product_id = productVo.getId();
        mallAttrConnectService.removeConnect(product_id);

        String name = CreateOrUpdateProduct(productVo, false);
        updateProductPriceRange(product_id, productVo);
        CreateOrUpdateAttrConnect(product_id, productVo);
        //return ServerResponse.createBySuccess("创建成功");
        return ServerResponse.createBySuccess(name, product_id);
    }

    private String CreateOrUpdateProduct(BProductVo productVo, boolean isCreate) {
        // 设置产品信息
        MallProduct product = new MallProduct();
        String name = productVo.getCategory() + "," + productVo.getGloss() + "," + productVo.getModel() + ","
                + productVo.getFineness() + "," + "/" + productVo.getPore_number() + "," + productVo.getSingle_share() + ","
                + productVo.getColor() + "," + productVo.getSection() + "," + productVo.getNetwork() + "," + productVo.getTwisting() + ",";
        product.setMainImage(productVo.getMain_image());
        product.setName(name);
        product.setSubtitle(productVo.getSubtitle());
        product.setSubImages(productVo.getSub_image());
        product.setDetail(productVo.getDetail());
        product.setContent(productVo.getContent());
        product.setStock(productVo.getStock());
        product.setTitle(productVo.getTitle());
        // 这是category id是空的
        product.setPrice(BigDecimal.valueOf(20));
        product.setTitle(productVo.getTitle());
        product.setCategoryId(productVo.getCategoryId());
        //暂时设为1
        product.setShopId(1);
        Date now = new Date();
        if (isCreate) product.setCreateTime(now);
        else product.setUpdateTime(now);
        product.setIsnew(productVo.getIsnew());
        product.setStatus(productVo.getStatus());
        if (!isCreate) product.setId(productVo.getId());
        MallAttrValue value = new MallAttrValue();
        // 设置分类
        int resultCount = mallAttrConnectService.checkCategory(productVo.getCategory().trim());
        value.setParentId(6);
        value.setValue(productVo.getCategory());
        if (resultCount == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setCategoryId(mallAttrConnectService.findId(value));
        product.setCategoryId(productVo.getCategoryId());

        // 设置纤度
        int resultCount2 = mallAttrConnectService.checkFineness(productVo.getFineness());
        //value=new MallAttrValue();
        value.setParentId(3);
        value.setValue(productVo.getFineness());
        if (resultCount2 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setFinenessId(mallAttrConnectService.findId(value));

        // 设置光泽
        int resultCount3 = mallAttrConnectService.checkGloss(productVo.getGloss());
        value.setParentId(1);
        value.setValue(productVo.getGloss());
        if (resultCount3 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setGlossId(mallAttrConnectService.findId(value));

        // 设置截面
        int resultCount4 = mallAttrConnectService.checkSection(productVo.getSection());
        value.setParentId(2);
        value.setValue(productVo.getSection());
        if (resultCount4 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setSectionId(mallAttrConnectService.findId(value));

        // 设置孔数
        int resultCount5 = mallAttrConnectService.checkPore_numberId(productVo.getPore_number());
        value.setParentId(4);
        value.setValue(productVo.getPore_number());
        if (resultCount5 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setPore_numberId(mallAttrConnectService.findId(value));

        // 设置单双股
        int resultCount6 = mallAttrConnectService.checkSingle_shareId(productVo.getSingle_share());
        value.setParentId(5);
        value.setValue(productVo.getSingle_share());
        if (resultCount6 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setSingle_shareId(mallAttrConnectService.findId(value));

        // 设置型号
        int resultCount7 = mallAttrConnectService.checkModel(productVo.getModel());
        value.setParentId(7);
        value.setValue(productVo.getModel());
        if (resultCount7 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setModelId(mallAttrConnectService.findId(value));

        //设置颜色
        int resultCount8 = mallAttrConnectService.checkColor(productVo.getColor());
        value.setParentId(9);
        value.setValue(productVo.getColor());
        if (resultCount8 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setColorId(mallAttrConnectService.findId(value));

        // 设置捻向
        int resultCount10 = mallAttrConnectService.checkTwisting(productVo.getTwisting().trim());
        value.setParentId(64);
        value.setValue(productVo.getTwisting());
        if (resultCount10 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setTwistingId(mallAttrConnectService.findId(value));

        // 设置网络
        int resultCount11 = mallAttrConnectService.checkNetwork(productVo.getNetwork().trim());
        value.setParentId(65);
        value.setValue(productVo.getNetwork());
        if (resultCount11 == 0) {
            value.setSeque(0);
            mallAttrConnectService.myInsert(value);
        }
        productVo.setNetworkId(mallAttrConnectService.findId(value));


        //设置等级
        if (productVo.getPrice_list() != null) {
            productVo.getPrice_list().forEach(item -> {
                System.out.println(item.toString());
                int resultCount9 = mallAttrConnectService.checkGrade(item.getGrade());
                value.setParentId(8);
                value.setValue(item.getGrade());
                if (resultCount9 == 0) {
                    value.setSeque(0);
                    mallAttrConnectService.myInsert(value);
                }
            });
        }
        // ?
        productVo.setGradeId(mallAttrConnectService.findId(value));

        System.out.println("产品ID->" + product.getId() + "标志：" + isCreate);

        iProductService.saveOrUpdateProduct(product);
        name = name + ",";
        return name;
    }

    private void updateProductPriceRange(Integer product_id, BProductVo productVo) {
        List<MallPrice> mallPriceList = new ArrayList<>();
        if (productVo.getPrice_list() != null) {
            productVo.getPrice_list().forEach(item -> {
                // 1条要变成4条记录，1个产品最多生成24条记录，都是0的数据不插入进数据库
                if (item.getPrice1().intValue() > 0 && item.getPrice2().intValue() > 0 &&
                        item.getPrice().intValue() > 0 && item.getPrice3().intValue() > 0 &&
                        item.getPrice4().intValue() > 0) {

                    for (int i = 0; i < 4; i++) {
                        MallPrice price = new MallPrice();
                        price.setProductId(product_id);
                        price.setGrade(item.getGrade());
                        if (i == 0) {
                            price.setPriceStart(0);
                            price.setPriceEnd(1000);
                        }
                        if (i == 1) {
                            price.setPriceStart(1000);
                            price.setPriceEnd(10000);
                        }
                        if (i == 2) {
                            price.setPriceStart(10000);
                            price.setPriceEnd(22000);
                        }
                        if (i == 3) {
                            price.setPriceStart(22000);
                            price.setPriceEnd(999999999);
                        }
                        if (price.getPriceEnd() == 1000) price.setPriceNum(item.getPrice1());
                        if (price.getPriceEnd() == 10000) price.setPriceNum(item.getPrice2());
                        if (price.getPriceEnd() == 22000) price.setPriceNum(item.getPrice3());
                        if (price.getPriceEnd() == 999999999) price.setPriceNum(item.getPrice4());
                        System.out.println("新建价格:{" + price.getProductId() + "," + price.getGrade() + ","
                                + price.getPriceStart() + "," + price.getPriceEnd() + "," + price.getPriceNum());
                        mallPriceList.add(price);
                    }
                } else {
                    mallPriceService.deleteByGradeAndId(item.getGrade(), product_id);
                    System.out.println(item.getGrade() + " 对应的价格为0，忽略！");
                }
            });
        }
        List<MallPrice> priceList = mallPriceService.findPriceRange(product_id);
        if (priceList == null || priceList.size() == 0)
            mallPriceService.add(mallPriceList);
        else {
            // 从传入的价格列表里找出原有价格表没有的记录，存入gapPriceList,这些是要新插入数据库里的
            List<MallPrice> gapPriceList = new ArrayList<>();
            for (MallPrice aMallPriceList : mallPriceList) {
                int count = 0;
                for (MallPrice aPriceList : priceList) {
                    System.out.println(aMallPriceList.getGrade().equals(aPriceList.getGrade()) && aMallPriceList.getPriceEnd().equals(aPriceList.getPriceEnd()) && aMallPriceList.getPriceStart().equals(aPriceList.getPriceStart()));
                    if (aMallPriceList.getGrade().equals(aPriceList.getGrade()) && aMallPriceList.getPriceEnd().equals(aPriceList.getPriceEnd()) && aMallPriceList.getPriceStart().equals(aPriceList.getPriceStart())) {
                        count++;
                    }
                }
                if (count == 0) {
                    gapPriceList.add(aMallPriceList);
                    System.out.println("插入更新价格:" + aMallPriceList.getPriceNum() + ",产品等级：" + aMallPriceList.getGrade());
                }
            }


            // 原有的价格表里找出有价格变化的，把价格更新。
            priceList.forEach(item -> mallPriceList.forEach(itemNew -> {
                if (item.getGrade().equals(itemNew.getGrade()) &&
                        item.getPriceEnd().equals(itemNew.getPriceEnd()) &&
                        item.getPriceStart().equals(itemNew.getPriceStart())) {
                    if (!item.getPriceNum().equals(itemNew.getPriceNum())) {
                        System.out.println("更新价格:" + item.getPriceNum() + "->" + itemNew.getPriceNum());
                        item.setPriceNum(itemNew.getPriceNum());
                    }
                }
            }));
            mallPriceService.update(priceList);
            if (gapPriceList.size() > 0) mallPriceService.add(gapPriceList);
        }
    }

    private void CreateOrUpdateAttrConnect(Integer product_id, BProductVo productVo) {
        MallAttrConnect connect = new MallAttrConnect();
        connect.setProductId(product_id);
        connect.setAttrId(productVo.getCategoryId());
        connect.setAttrValue(productVo.getCategory());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getFinenessId());
        connect.setAttrValue(productVo.getFineness());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getGlossId());
        connect.setAttrValue(productVo.getGloss());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getSectionId());
        connect.setAttrValue(productVo.getSection());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getPore_numberId());
        connect.setAttrValue(productVo.getPore_number());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getSingle_shareId());
        connect.setAttrValue(productVo.getSingle_share());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getModelId());
        connect.setAttrValue(productVo.getModel());
        mallAttrConnectService.saveAttrConnect(connect);
        //  connect.setAttrId(productVo.getGradeId());
        //   connect.setAttrValue(productVo.getGrade());
        connect.setAttrId(productVo.getColorId());
        connect.setAttrValue(productVo.getColor());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getNetworkId());
        connect.setAttrValue(productVo.getNetwork());
        mallAttrConnectService.saveAttrConnect(connect);
        connect.setAttrId(productVo.getTwistingId());
        connect.setAttrValue(productVo.getTwisting());
        mallAttrConnectService.saveAttrConnect(connect);
    }

    @PostMapping("GetProducts")
    @ApiOperation(value = "获得产品信息")
    public ServerResponse GetProduct(Integer id) {
        System.out.println("产品ID" + id);
        return mallAttrConnectService.findByProductId(id);
    }

    @AuthRequired
    @PostMapping("CheckModel")
    @ApiOperation(value = "检查型号是否重复")
    public ServerResponse CheckModel(String model) {
        System.out.println(model);
        int count = mallAttrConnectService.checkModel(model);
        System.out.println(count);
        if (count != 0) {
            int productId = mallAttrConnectService.findProductIdByModel(model);
            return ServerResponse.createBySuccess("重复产品", productId);
        }
        return ServerResponse.createBySuccess("未重复");
    }

    @AuthRequired
    @PostMapping("SaveAttrValue")
    @ApiOperation(value = "保存属性")
    public ServerResponse<String> SaveAttrValue(@RequestBody MyAttrValueVo myAttrValueVo) {
        System.out.println(myAttrValueVo.toString());
        Integer parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "category");
        String[] oldList = mallAttrValueMapper.selectValueById(parent_id);
        System.out.println(Arrays.toString(oldList));
        for (int i = 0; i < myAttrValueVo.getTwising().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getTwising()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getTwising()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (int i = 0; i < myAttrValueVo.getNetwork().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getNetwork()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getNetwork()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (int i = 0; i < myAttrValueVo.getCategory().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getCategory()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getCategory()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getCategory().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getCategory()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getCategory().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "color");
        oldList = mallAttrValueMapper.selectValueById(parent_id);
        for (int i = 0; i < myAttrValueVo.getColor().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getColor()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getColor()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getColor().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getColor()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getColor().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "gloss");
        oldList = mallAttrValueMapper.selectValueById(parent_id);
        for (int i = 0; i < myAttrValueVo.getGloss().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getGloss()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getGloss()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getGloss().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getGloss()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getGloss().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "grade");
        oldList = mallAttrValueMapper.selectValueById(parent_id);
        for (int i = 0; i < myAttrValueVo.getGrade().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getGrade()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getGrade()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getGrade().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getGrade()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getGrade().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "section");
        oldList = mallAttrValueMapper.selectValueById(parent_id);
        for (int i = 0; i < myAttrValueVo.getSection().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getSection()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getSection()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getSection().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getSection()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getSection().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        parent_id = mallAttrMapper.selectIdByDeptId(myAttrValueVo.getDept_id(), "single_share");
        oldList = mallAttrValueMapper.selectValueById(parent_id);
        for (int i = 0; i < myAttrValueVo.getSingle_share().length; i++) {
            int count = 0;
            for (String anOldList : oldList) {
                if (!myAttrValueVo.getSingle_share()[i].equals(anOldList)) {
                    count++;
                }
            }
            if (count == oldList.length) {
                MallAttrValue mallAttrValue = new MallAttrValue();
                mallAttrValue.setParentId(parent_id);
                mallAttrValue.setSeque(0);
                mallAttrValue.setValue(myAttrValueVo.getSingle_share()[i]);
                mallAttrValueMapper.insert(mallAttrValue);
            }
        }
        for (String anOldList : oldList) {
            int count = 0;
            for (int j = 0; j < myAttrValueVo.getSingle_share().length; j++) {
                if (!anOldList.equals(myAttrValueVo.getSingle_share()[j])) {
                    count++;
                }
            }
            if (count == myAttrValueVo.getSingle_share().length) {
                mallAttrValueMapper.deleteByValueAndId(anOldList, parent_id);
            }
        }
        return ServerResponse.createBySuccess("ok");
    }

    @AuthRequired
    @GetMapping("GetMyAttrValueList")
    @ApiOperation(value = "获得属性列表")
    public ServerResponse<MyAttrValueVo> GetMyAttrValueList(Integer dept_id) {
        Integer parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "category");
        String[] categoryList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "gloss");
        String[] glossList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "section");
        String[] sectionList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "single_share");
        String[] singleShareList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "grade");
        String[] gradeList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "color");
        String[] colorList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "network");
        String[] networkList = mallAttrValueMapper.selectValueById(parent_id);
        parent_id = mallAttrMapper.selectIdByDeptId(dept_id, "twising");
        String[] twisingList = mallAttrValueMapper.selectValueById(parent_id);
        MyAttrValueVo myAttrValueVo = new MyAttrValueVo();
        myAttrValueVo.setCategory(categoryList);
        myAttrValueVo.setGloss(glossList);
        myAttrValueVo.setColor(colorList);
        myAttrValueVo.setGrade(gradeList);
        myAttrValueVo.setSection(sectionList);
        myAttrValueVo.setSingle_share(singleShareList);
        myAttrValueVo.setNetwork(networkList);
        myAttrValueVo.setTwising(twisingList);
        return ServerResponse.createBySuccess(myAttrValueVo);
    }

    @AuthRequired
    @GetMapping("SearchProduct")
    @ApiOperation(value = "搜索产品")
    public ServerResponse<PageInfo<MallProduct>> SearchProduct(String query, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                               @RequestParam(value = "pageSize", defaultValue = "100") int pageSize) {
        System.out.println(query);
        PageHelper.startPage(pageNum, pageSize);
        System.out.println(query);
        List<MallProduct> productList = mallProductMapper.selectListByName2(query);

        PageInfo<MallProduct> pageResult = new PageInfo<>(productList);
        return ServerResponse.createBySuccess(pageResult);
    }

    @GetMapping("updateCMSIndex")
    @ApiOperation(value = "增加文章索引")
    public void updateCMSIndex() {

        String result = HttpClientUtil.doPostWithParam("http://47.98.213.218:3333/api/cms/GetArticleListWithContent");
        Gson gson = new Gson();
        System.out.println(result);
        Map map = new HashMap<String, Object>();
        map = gson.fromJson(result, map.getClass());
        System.out.println(map);
        JSONArray jsonArray = JSONArray.fromObject(map.get("Data"));
        System.out.println(jsonArray.size());
        for (Object aJsonArray : jsonArray) {
            CMS cms = (CMS) JSONObject.toBean((JSONObject) aJsonArray, CMS.class);
            Map<String, String> map2 = new HashMap<>();
            map2.put("name", "id");
            map2.put("value", cms.getId().toString());
            System.out.println("**********");
            System.out.println("查找文章id为" + cms.getId());
            String result2 = HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/searchCMSByAttr", map2);
            if (result2.equals("[]")) {
                System.out.println("添加文章id为" + cms.getId());
                System.out.println("**********");
                Map<String, String> map3 = new HashMap<>();
                map3.put("id", cms.getId().toString());
                map3.put("end_date", cms.getEnd_date());
                map3.put("article_title", cms.getArticle_title());
                StringBuilder image_url = new StringBuilder();
                for (int j = 0; j < cms.getImage_url().length; j++) {
                    image_url.append(cms.getImage_url()[j]);
                }
                map3.put("image_url", image_url.toString());
                map3.put("article_url", cms.getArticle_url());
                map3.put("create_date", cms.getCreate_date());
                map3.put("type", cms.getType());
                map3.put("content", "");
                map3.put("start_date", cms.getStart_date());
                map3.put("status", cms.getStatus().toString());
                HttpClientUtil.doPostWithParam("http://47.98.171.71:8081/hdfind/createCMSAll", map3);
            }
        }
        System.out.println("添加文章索引完成");
    }

    @GetMapping("updateCMSIndex2")
    @ApiOperation(value = "更新和删除文章索引")
    public void updateCMSIndex2() {
        String indexList = HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/allCMS");
        JSONArray jsonArray2 = JSONArray.fromObject(indexList);
        for (Object aJsonArray2 : jsonArray2) {
            CMSVO cms = (CMSVO) JSONObject.toBean((JSONObject) aJsonArray2, CMSVO.class);
            Map map = new HashMap<String, String>();
            map.put("Id", cms.getId());
            String result = HttpClientUtil.doPostWithParam("http://47.98.213.218:3333/api/cms/GetArticle2", map);
            System.out.println(result);
            if (result.equals("{\"Code\":0,\"Message\":\"ok\",\"Data\":1,\"total\":null}")) {
                Map<String, String> map2 = new HashMap<>();
                map.put("id", cms.getId());
                System.out.println("删除文章id=" + cms.getId());
                HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/deleteCMS", map);
            } else {
                Gson gson = new Gson();
                Map<String, Object> map2 = new HashMap<String, Object>();
                map = gson.fromJson(result, map2.getClass());
                JSONArray jsonArray = JSONArray.fromObject(map.get("Data"));
                CMS cms2 = (CMS) JSONObject.toBean((JSONObject) jsonArray.get(0), CMS.class);
                StringBuilder image_url = new StringBuilder();
                for (int t = 0; t < cms2.getImage_url().length; t++) {
                    image_url.append(cms2.getImage_url()[t]);
                }
                if (cms.getArticle_title().equals(cms2.getArticle_title()) && cms.getArticle_url().equals(cms2.getArticle_url()) && cms.getCreate_date().equals(cms2.getCreate_date()) && cms.getEnd_date().equals(cms2.getEnd_date()) && cms.getStart_date().equals(cms2.getStart_date()) && cms.getStatus().equals(cms2.getStatus().toString()) && cms.getType().equals(cms2.getType()) && cms.getImage_url().equals(image_url.toString())) {
                    System.out.println("无更新id=" + cms2.getId());
                } else {
                    Map<String, String> map3 = new HashMap<>();
                    map3.put("id", cms2.getId().toString());
                    map3.put("end_date", cms2.getEnd_date());
                    map3.put("article_title", cms2.getArticle_title());
                    String image_url2 = "";
                    for (int j = 0; j < cms2.getImage_url().length; j++) {
                        image_url.append(cms2.getImage_url()[j]);
                    }
                    map3.put("image_url", image_url2);
                    map3.put("article_url", cms2.getArticle_url());
                    map3.put("create_date", cms2.getCreate_date());
                    map3.put("type", cms2.getType());
                    map3.put("content", "");
                    map3.put("start_date", cms2.getStart_date());
                    map3.put("status", cms2.getStatus().toString());
                    System.out.println("更新文章记录id" + map3.get("id"));
                    HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/updateCMSAll", map);
                }
            }
            System.out.println("****************");
        }
    }

    @GetMapping("updateIndex")
    @ApiOperation(value = "更新产品索引")
    public void updateIndex() {
        String indexList = HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/all");
        System.out.println(indexList);
        JSONArray jsonArray = JSONArray.fromObject(indexList);
        for (Object aJsonArray : jsonArray) {
            Document document = (Document) JSONObject.toBean((JSONObject) aJsonArray, Document.class);
            MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(Integer.parseInt(document.getId()));
            if (mallProduct == null) {
                Map<String, String> deleteMap = new HashMap<>();
                deleteMap.put("id", document.getId());
                System.out.println("删除记录id=" + document.getId());
                HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/delete", deleteMap);
            }
        }
        System.out.println("执行删除完成");
        List<MallProduct> list = mallProductMapper.selectList();
        for (MallProduct aList : list) {
            Map<String, String> map = new HashMap<>();
            map.put("name", "id");
            map.put("value", aList.getId().toString());
            String result = HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/searchByAttr", map);
            if (result.equals("[]")) {
                System.out.println("新增产品" + aList.getId());
                Map<String, String> map2 = new HashMap<>();
                String[] as = aList.getName().split(",");
                map2.put("category", as[0]);
                map2.put("gloss", as[1]);
                map2.put("model", as[2]);
                map2.put("fineness", as[3]);
                map2.put("pore_number", as[4]);
                map2.put("single_share", as[5]);
                map2.put("color", as[6]);
                map2.put("section", as[7]);
                map2.put("name", aList.getName());
                map2.put("main_image", aList.getMainImage());
                map2.put("status", aList.getStatus().toString());
                map2.put("stock", aList.getStock().toString());
                map2.put("subtitle", aList.getSubtitle());
                map2.put("id", aList.getId().toString());
                HttpClientUtil.doPostWithParam("http://47.98.171.71:8081/hdfind/createAll", map2);
            } else {
                String[] as = aList.getName().split(",");
                jsonArray = JSONArray.fromObject(result);
                Document document = (Document) JSONObject.toBean((JSONObject) jsonArray.get(0), Document.class);
                if (!(document.getCategory().equals(as[0])
                        && document.getGloss().equals(as[1])
                        && document.getModel().equals(as[2])
                        && document.getFineness().equals(as[3])
                        && document.getPore_number().equals(as[4])
                        && document.getSingle_share().equals(as[5])
                        && document.getColor().equals(as[6])
                        && document.getSection().equals(as[7])
                        && document.getName().equals(aList.getName())
                        && document.getMain_image().equals(aList.getMainImage())
                        && document.getStatus().equals(aList.getStatus().toString())
                        && document.getStock().equals(aList.getStock().toString())
                        && document.getSubtitle().equals(aList.getSubtitle())
                        && document.getId().equals(aList.getId().toString()))) {
                    System.out.println("更新产品" + aList.getId());
                    Map<String, String> map2 = new HashMap<>();
                    String[] as2 = aList.getName().split(",");
                    map2.put("category", as2[0]);
                    map2.put("gloss", as2[1]);
                    map2.put("model", as2[2]);
                    map2.put("fineness", as2[3]);
                    map2.put("pore_number", as2[4]);
                    map2.put("single_share", as2[5]);
                    map2.put("color", as2[6]);
                    map2.put("section", as2[7]);
                    map2.put("name", aList.getName());
                    map2.put("main_image", aList.getMainImage());
                    map2.put("status", aList.getStatus().toString());
                    map2.put("stock", aList.getStock().toString());
                    map2.put("subtitle", aList.getSubtitle());
                    map2.put("id", aList.getId().toString());
                    HttpClientUtil.doPostWithParam("http://47.98.171.71:8081/hdfind/updateAll", map2);
                }
//                System.out.println(document.getName());
            }
        }
    }

    @AuthRequired
    @GetMapping("getPath")
    @ApiOperation(value = "ftp获得路径")
    public void getPath(String url, int port, String username, String password, String path) {
        FtpClient ftp;
        ArrayList<String> arFiles = null;
        InputStream is = null;

        FileOutputStream fos = null;
        try {
            //创建地址
            SocketAddress addr = new InetSocketAddress(url, port);
            //连接
            ftp = FtpClient.create();
            ftp.connect(addr);
            //登陆
            ftp.login(username, password.toCharArray());
            ftp.setBinaryType();
            System.out.println(ftp);
            //Iterable iter = (Iterable) ftp.listFiles("/");
            Iterator<FtpDirEntry> it = ftp.listFiles(path);
            while (it.hasNext()) {
                FtpDirEntry a = it.next();
                System.out.println("path:" + "/" + path + a.getName() + "  time:" + a.getLastModified());
            }
        } catch (FtpProtocolException | IOException e) {
            e.printStackTrace();
        }
    }

    @AuthRequired
    @GetMapping("downloadFile")
    @ApiOperation(value = "ftp下载文件")
    public HttpServletResponse downloadFile(String url, int port, String username, String password, String localFile, String ftpFile, HttpServletResponse response) {
        FtpClient ftp;
        ArrayList<String> arFiles = null;
        InputStream is;

        FileOutputStream fos;
        try {
            //创建地址
            SocketAddress addr = new InetSocketAddress(url, port);
            //连接
            ftp = FtpClient.create();
            ftp.connect(addr);
            //登陆
            ftp.login(username, password.toCharArray());
            ftp.setBinaryType();
            System.out.println(ftp);
            //Iterable iter = (Iterable) ftp.listFiles("/");
            Iterator<FtpDirEntry> it = ftp.listFiles("/hd-admin每日更新");
            while (it.hasNext()) {
                FtpDirEntry a = it.next();
                System.out.println("name:" + a.getName() + "  time:" + a.getLastModified());
            }

            is = ftp.getFileStream(ftpFile);
            File file = new File(localFile);
            byte[] bytes = new byte[1024];
            int i;
            fos = new FileOutputStream(file);
            while ((i = is.read(bytes)) != -1) {
                fos.write(bytes, 0, i);
            }
            fos.close();
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(localFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            file.delete();
        } catch (FtpProtocolException | IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    @AuthRequired
    @GetMapping("test")
    @ApiOperation(value = "test")
    public void test() {
        List<MallProduct> list = mallProductMapper.selectTest();
//        List<MallProduct> list = mallProductMapper.selectTest2();
        for (MallProduct aList : list) {
            MallPrice mallPrice = new MallPrice();
            mallPrice.setProductId(aList.getId());
            mallPrice.setPriceStart(0);
            mallPrice.setPriceEnd(1000);
            mallPrice.setGrade("AA");
            mallPrice.setPriceNum(new BigDecimal(20));
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(1000);
            mallPrice.setPriceEnd(10000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(10000);
            mallPrice.setPriceEnd(22000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(22000);
            mallPrice.setPriceEnd(999999999);
            mallPriceMapper.insert(mallPrice);

//            mallPrice.setPriceStart(0);
//            mallPrice.setPriceEnd(1000);
//            mallPrice.setGrade("AA定重");
//            mallPrice.setPriceNum(new BigDecimal(20));
//            mallPriceMapper.insert(mallPrice);
//            mallPrice.setPriceStart(1000);
//            mallPrice.setPriceEnd(10000);
//            mallPriceMapper.insert(mallPrice);
//            mallPrice.setPriceStart(10000);
//            mallPrice.setPriceEnd(22000);
//            mallPriceMapper.insert(mallPrice);
//            mallPrice.setPriceStart(22000);
//            mallPrice.setPriceEnd(999999999);
//            mallPriceMapper.insert(mallPrice);

            mallPrice.setPriceStart(0);
            mallPrice.setPriceEnd(1000);
            mallPrice.setGrade("A");
            mallPrice.setPriceNum(new BigDecimal(20));
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(1000);
            mallPrice.setPriceEnd(10000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(10000);
            mallPrice.setPriceEnd(22000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(22000);
            mallPrice.setPriceEnd(999999999);
            mallPriceMapper.insert(mallPrice);

            mallPrice.setPriceStart(0);
            mallPrice.setPriceEnd(1000);
            mallPrice.setGrade("B");
            mallPrice.setPriceNum(new BigDecimal(20));
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(1000);
            mallPrice.setPriceEnd(10000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(10000);
            mallPrice.setPriceEnd(22000);
            mallPriceMapper.insert(mallPrice);
            mallPrice.setPriceStart(22000);
            mallPrice.setPriceEnd(999999999);
            mallPriceMapper.insert(mallPrice);
        }
    }

    @PostMapping("updateStock")
    @ApiOperation(value = "更新库存表")
    public ServerResponse<List> updateStock(MultipartFile file,
                                            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);

        List list = ReadExcel.readExcel(tempFile);

        assert list != null;
        list.remove(0);
        list.remove(0);
        list.remove(list.size() - 1);
        List<String> list1 = new ArrayList<>();

        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            list1.add(taskList.get(0) + "," + taskList.get(2) + "," + taskList.get(6) + "," + taskList.get(7) + "," + taskList.get(8) + "," + taskList.get(9));
            MallProductForwardStock mallProductForwardStock1 = mallProductForwardStockMapper.selectForwardStock(taskList.get(0), taskList.get(2), taskList.get(6), taskList.get(7), taskList.get(8), taskList.get(9));
            if (mallProductForwardStock1 == null) {
                MallProductForwardStock mallProductForwardStock = new MallProductForwardStock();
                mallProductForwardStock.setColor(taskList.get(8));
                mallProductForwardStock.setMachineNo(taskList.get(9));
                mallProductForwardStock.setInventoryOrganization(taskList.get(0));
                mallProductForwardStock.setFactory(taskList.get(1));
                mallProductForwardStock.setMaterialCode(taskList.get(2));
                mallProductForwardStock.setMaterialName(taskList.get(3));
                mallProductForwardStock.setSpecifications(taskList.get(4));
                mallProductForwardStock.setModel(taskList.get(5));
                mallProductForwardStock.setGradeInfo(taskList.get(10));
                mallProductForwardStock.setMachineType(taskList.get(11));
                mallProductForwardStock.setNetworkPly(taskList.get(12));
                mallProductForwardStock.setGrade(taskList.get(6));
                mallProductForwardStock.setTwisting(taskList.get(7));
                mallProductForwardStock.setStatus(taskList.get(15));
                mallProductForwardStock.setCanBuyNumber(taskList.get(16));
                mallProductForwardStock.setBuyNumber(taskList.get(17));
                mallProductForwardStock.setSendNumber(taskList.get(18));
                mallProductForwardStock.setWaitOutNumber(taskList.get(19));
                mallProductForwardStock.setWaitInNumber(taskList.get(20));
                mallProductForwardStock.setStock(taskList.get(21));
                mallProductForwardStock.setStockBoxNumber(taskList.get(22));
                mallProductForwardStock.setSortCode(taskList.get(23));
                mallProductForwardStock.setSortName(taskList.get(24));
                mallProductForwardStockMapper.insert(mallProductForwardStock);
            } else if (!(
                    mallProductForwardStock1.getCanBuyNumber().equals(taskList.get(16))
                            && mallProductForwardStock1.getBuyNumber().equals(taskList.get(17))
                            && mallProductForwardStock1.getSendNumber().equals(taskList.get(18))
                            && mallProductForwardStock1.getWaitOutNumber().equals(taskList.get(19))
                            && mallProductForwardStock1.getWaitInNumber().equals(taskList.get(20))
                            && mallProductForwardStock1.getStock().equals(taskList.get(21))
            )) {
                mallProductForwardStock1.setColor(taskList.get(8));
                mallProductForwardStock1.setMachineNo(taskList.get(9));
                mallProductForwardStock1.setFactory(taskList.get(1));
                mallProductForwardStock1.setMaterialName(taskList.get(3));
                mallProductForwardStock1.setSpecifications(taskList.get(4));
                mallProductForwardStock1.setModel(taskList.get(5));
                mallProductForwardStock1.setGradeInfo(taskList.get(10));
                mallProductForwardStock1.setMachineType(taskList.get(11));
                mallProductForwardStock1.setNetworkPly(taskList.get(12));
                mallProductForwardStock1.setGrade(taskList.get(6));
                mallProductForwardStock1.setTwisting(taskList.get(7));
                mallProductForwardStock1.setStatus(taskList.get(15));
                mallProductForwardStock1.setCanBuyNumber(taskList.get(16));
                mallProductForwardStock1.setBuyNumber(taskList.get(17));
                mallProductForwardStock1.setSendNumber(taskList.get(18));
                mallProductForwardStock1.setWaitOutNumber(taskList.get(19));
                mallProductForwardStock1.setWaitInNumber(taskList.get(20));
                mallProductForwardStock1.setStock(taskList.get(21));
                mallProductForwardStock1.setStockBoxNumber(taskList.get(22));
                mallProductForwardStock1.setSortCode(taskList.get(23));
                mallProductForwardStock1.setSortName(taskList.get(24));
                mallProductForwardStockMapper.updateByPrimaryKey(mallProductForwardStock1);
            }
        }
        List<MallProductForwardStock> list2 = mallProductForwardStockMapper.selectAll();
        for (MallProductForwardStock aList2 : list2) {
            if (!(list1.contains(aList2.getInventoryOrganization() + "," + aList2.getMaterialCode() + "," + aList2.getGrade() + "," + aList2.getTwisting() + "," + aList2.getColor() + "," + aList2.getMachineNo()))) {
                mallProductForwardStockMapper.deleteByPrimaryKey(aList2);
            }
        }
        return ServerResponse.createBySuccess(list);
    }

    static File getFile(MultipartFile file, HttpServletRequest request, File tempFile) throws IOException {
        if (!file.isEmpty()) {
            String filePath = request.getSession().getServletContext()
                    .getRealPath("/") + "upload/";
            File dir = new File(filePath);

            if (!dir.exists()) {
                dir.mkdir();
            }

            String path = filePath + file.getOriginalFilename();
            //save to the /upload path
            tempFile = new File(path);

            file.transferTo(tempFile);
        }
        return tempFile;
    }

    @PostMapping("updateInStorage")
    @ApiOperation(value = "更新入库表")
    public ServerResponse<String> updateInStorage(MultipartFile file,
                                                  HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);

        List list = ReadExcel.readExcel(tempFile);

        assert list != null;
        list.remove(0);
        list.remove(list.size() - 1);

        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            Integer count = mallProductInStorageMapper.selectByFufillmentNo(taskList.get(0));
            if (count <= 0) {
                MallProductInStorage mallProductInStorage = new MallProductInStorage();
                mallProductInStorage.setFufillmentNo(taskList.get(0));
                mallProductInStorage.setFufillmentTime(taskList.get(1));
                mallProductInStorage.setPkGroup(taskList.get(2));
                mallProductInStorage.setFactoryName(taskList.get(3));
                mallProductInStorage.setInventoryOrganization(taskList.get(4));
                mallProductInStorage.setRemark(taskList.get(5));
                mallProductInStorage.setMaterialCode(taskList.get(6));
                mallProductInStorage.setMaterialName(taskList.get(7));
                mallProductInStorage.setMemoryCode(taskList.get(8));
                mallProductInStorage.setSpecifications(taskList.get(9));
                mallProductInStorage.setModel(taskList.get(10));
                mallProductInStorage.setMachineType(taskList.get(11));
                mallProductInStorage.setNetworkAndPly(taskList.get(12));
                mallProductInStorage.setGrade(taskList.get(13));
                mallProductInStorage.setTwising(taskList.get(14));
                mallProductInStorage.setWeight(new BigDecimal(taskList.get(15)));
                mallProductInStorage.setBox(new BigDecimal(taskList.get(16)));
                mallProductInStorageMapper.insert(mallProductInStorage);
            }
        }

        return ServerResponse.createBySuccess("更新入库表成功");
    }

    @PostMapping("updateCustomerDetail")
    @ApiOperation(value = "更新客户详情表")
    public ServerResponse<String> updateCustomerDetail(MultipartFile file,
                                                       HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);

        List list = ReadExcel.readExcel(tempFile);

        assert list != null;
        list.remove(0);
        list.remove(0);
        list.remove(0);
        list.remove(0);
        list.remove(0);
        list.remove(0);
        list.remove(list.size() - 1);

        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            SysCustomerDetail sysCustomerDetail = new SysCustomerDetail();
            sysCustomerDetail.setOrganisation(taskList.get(0));
            sysCustomerDetail.setCustomerCode(taskList.get(1));
            sysCustomerDetail.setBusName(taskList.get(2));
            sysCustomerDetail.setShortName(taskList.get(3));
            sysCustomerDetail.setMemoryCode(taskList.get(4));
            sysCustomerDetail.setCustomerCategory(taskList.get(5));
            sysCustomerDetail.setSalesmanName(taskList.get(6));
            sysCustomerDetail.setStatus(taskList.get(7));
            sysCustomerDetail.setSupplier(taskList.get(8));
            sysCustomerDetail.setCustomerType(taskList.get(9));
            sysCustomerDetail.setBusinessUnit(taskList.get(10));
            sysCustomerDetail.setTaxNum(taskList.get(11));
            sysCustomerDetail.setSuperiorCustomer(taskList.get(12));
            sysCustomerDetail.setEnabled(taskList.get(13));
            sysCustomerDetailMapper.insert(sysCustomerDetail);
        }

        return ServerResponse.createBySuccess("更新客户详情表成功");
    }

    @PostMapping("updatePrice")
    @ApiOperation(value = "更新价格表")
    public ServerResponse updatePrice(MultipartFile file,
                                      HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);


        List list = ReadExcel.readExcel(tempFile);
        assert list != null;
        list.remove(0);
        list.remove(0);

        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            String twisting = taskList.get(9);
            System.out.println("model=" + taskList.get(0));
            System.out.println("old twisting=" + twisting);
            if (twisting.equals("S") || twisting.equals("Z")) {
                twisting = twisting + "捻";
            } else {
                twisting = "无捻向";
            }
            System.out.println("new twisting=" + twisting);
            MallProductPrice mallProductPrice = new MallProductPrice();
            mallProductPrice.setModel(taskList.get(0));
            mallProductPrice.setMaterialCode(taskList.get(1));
            mallProductPrice.setMaterialName(taskList.get(2));
            mallProductPrice.setSpecifications(taskList.get(3));
            mallProductPrice.setStatus(taskList.get(4));
            mallProductPrice.setMemoryCode(taskList.get(5));
            mallProductPrice.setMachineType(taskList.get(6));
            mallProductPrice.setNetworkPly(taskList.get(7));
            mallProductPrice.setGrade(taskList.get(8));
            mallProductPrice.setTwisting(twisting);
            mallProductPrice.setGradeInfo(taskList.get(10));
            mallProductPrice.setLineNo(taskList.get(11));
            mallProductPrice.setCny1(taskList.get(12));
            mallProductPrice.setUsd(taskList.get(13));
            mallProductPrice.setCny2(taskList.get(14));
            mallProductPrice.setRemark(taskList.get(15));
            mallProductPrice.setPkMaterial(taskList.get(16));
            mallProductPriceMapper.insert(mallProductPrice);
        }

        return ServerResponse.createBySuccess();
    }


    @GetMapping("test2")
    @ApiOperation(value = "test")
    public void test2() {
        List<SysCustomerDetail> list = sysCustomerDetailMapper.selectBySalesManName("崔常升");
        for (SysCustomerDetail sysCustomerDetail : list) {
            if (!sysCustomerDetail.getBusName().equals("浙江宝娜斯袜业有限公司")) {
                SysCustomer sysCustomer = new SysCustomer();
                SysDept sysDept = new SysDept();
                sysDept.setName(sysCustomerDetail.getBusName());
                sysDept.setParentId(17);
                sysDept.setDelFlag("0");
                sysDept.setCreateTime(new Date());
                sysDeptMapper.insert(sysDept);
                Integer dept_id = sysDeptMapper.selectIdByName2(sysCustomerDetail.getBusName());
                sysCustomer.setBusName(sysCustomerDetail.getBusName());
                sysCustomer.setDealerId(18);
                sysCustomer.setSalesmanId(381);
                sysCustomer.setCreateTime(new Date());
                sysCustomerMapper.insert(sysCustomer);
                Integer customer_id = sysCustomerMapper.selectCustomerByName(sysCustomerDetail.getBusName());
                SysDeptCustomer sysDeptCustomer = new SysDeptCustomer();
                sysDeptCustomer.setCustomerId(customer_id);
                sysDeptCustomer.setDeptId(dept_id);
                sysDeptCustomerMapper.insert(sysDeptCustomer);
            }
        }
    }

    @AuthRequired
    @GetMapping("getStock")
    @ApiOperation(value = "获取库存信息")
    public ServerResponse<PageVo<MallProductForwardStock>> getStock(String code, Integer pageSize, Integer pageNum) {
        Integer pageStart = pageSize * (pageNum - 1);
        Integer total = mallProductForwardStockMapper.selectViewCount();
        List<MallProductForwardStock> mallProductStocks = mallProductForwardStockMapper.selectByCode(code, pageStart, pageSize);
        PageVo<MallProductForwardStock> pageVo = new PageVo<>(pageNum, pageSize, total, mallProductStocks);
        return ServerResponse.createBySuccess(pageVo);
    }

    @AuthRequired
    @GetMapping("viewStock")
    @ApiOperation(value = "查看库存信息")
    public ServerResponse<List<MallProductForwardStock>> viewStock(String name, String grade) {
        String[] s = name.split(",");
        String model = s[2];
        String twisting = s[9];
        String color = s[6];
        if (twisting.equals("Z捻") || twisting.equals("S捻")) {
            twisting = twisting.substring(0, twisting.length() - 1);
        }
        String[] a;
        switch (grade) {
            case "AA定重":
                a = new String[]{"AA定重", "AA1定重", "AA2定重", "AA3定重", "AA5定重", "AA6定重", "AA7定重", "AAA定重"};
                break;
            case "AA不定重":
                a = new String[]{"AA不定重", "AA1不定重", "AA2不定重", "AA3不定重", "AA5不定重", "AA6不定重", "AA7不定重"};
                break;
            default:
                a = new String[]{grade};
                break;
        }
        List<MallProductForwardStock> mallProductStocks = mallProductForwardStockMapper.selectByModelAndGrade(model, twisting, a, color);
        return ServerResponse.createBySuccess(mallProductStocks);
    }

    @AuthRequired
    @GetMapping("getPrice")
    @ApiOperation(value = "获取价格信息")
    public ServerResponse<PageVo<MallProductPrice>> getPrice(String code, Integer pageSize, Integer pageNum) {
        Integer pageStart = pageSize * (pageNum - 1);
        Integer total = mallProductPriceMapper.selectViewCount();
        List<MallProductPrice> mallProductPrices = mallProductPriceMapper.selectByCode(code, pageStart, pageSize);
        PageVo<MallProductPrice> pageVo = new PageVo<>(pageNum, pageSize, total, mallProductPrices);
        return ServerResponse.createBySuccess(pageVo);
    }

    @AuthRequired
    @GetMapping("viewPrice")
    @ApiOperation(value = "查看价格信息")
    public ServerResponse<List<MallProductPrice>> viewPrice(String name, String grade) {
        String[] s = name.split(",");
        String model = s[2];
        String twisting = s[9];
        List<MallProductPrice> mallProductPrices = mallProductPriceMapper.selectByModelAndGrade(model, twisting, grade);
        return ServerResponse.createBySuccess(mallProductPrices);
    }

    @GetMapping("update")
    @ApiOperation(value = "更新")
    public ServerResponse update() {
        List<MallProduct> list = mallProductMapper.selectAll();
        for (MallProduct mallProduct : list) {
            MallAttrConnect mallAttrConnect = new MallAttrConnect();
            mallAttrConnect.setProductId(mallProduct.getId());
            String[] s = mallProduct.getName().split(",");
            //插入类型
            mallAttrConnect.setAttrValue(s[0]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[0], 6));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入纤度
            mallAttrConnect.setAttrValue(s[3]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[3], 3));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入光泽
            mallAttrConnect.setAttrValue(s[1]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[1], 1));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入截面
            mallAttrConnect.setAttrValue(s[7]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[7], 2));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入孔数
            mallAttrConnect.setAttrValue(s[4].substring(1, s[4].length()));
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[4].substring(1, s[4].length()), 4));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入单合股
            mallAttrConnect.setAttrValue(s[5]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[5], 5));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入model
            mallAttrConnect.setAttrValue(s[2]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[2], 7));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入颜色
            mallAttrConnect.setAttrValue(s[6]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[6], 9));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入网络
            mallAttrConnect.setAttrValue(s[8]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[8], 65));
            mallAttrConnectMapper.insert(mallAttrConnect);
            //插入捻度
            mallAttrConnect.setAttrValue(s[9]);
            mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(s[9], 64));
            mallAttrConnectMapper.insert(mallAttrConnect);
        }
        return ServerResponse.createBySuccess();
    }

    @AuthRequired
    @GetMapping("viewOrderItemDetail")
    @ApiOperation(value = "查看产品物料编码列表")
    public ServerResponse<List<MallOrderItemDetail>> viewOrderItemDetail(Integer item_id) {
        List<MallOrderItemDetail> mallOrderItemDetailList = mallOrderItemDetailMapper.selectByItemId(item_id);
        return ServerResponse.createBySuccess(mallOrderItemDetailList);
    }

    @AuthRequired
    @PostMapping("addDetail")
    @ApiOperation(value = "添加详情")
    public ServerResponse addDetail(@RequestBody List<MallOrderItemDetail> list, Integer item_id) {
//        mallOrderItemDetailMapper.deleteByItemId(item_id);
        BigDecimal current_unit_price;
        BigDecimal quantity = new BigDecimal(0);
        BigDecimal total_price = new BigDecimal(0);
        for (MallOrderItemDetail mallOrderItemDetail : list) {
            MallOrderItemDetail mallOrderItemDetail1 = mallOrderItemDetailMapper.selectByCodeAndFactory(mallOrderItemDetail.getMaterialCode(), mallOrderItemDetail.getInventoryOrganization(), item_id, mallOrderItemDetail.getGrade(), mallOrderItemDetail.getColor(), mallOrderItemDetail.getTwisting(), mallOrderItemDetail.getMachineNo());
            if (mallOrderItemDetail1 != null) {
                mallOrderItemDetail1.setCurrentUnitPrice(mallOrderItemDetail.getCurrentUnitPrice());
                mallOrderItemDetail1.setQuantity(mallOrderItemDetail.getQuantity());
                mallOrderItemDetail1.setCheckQuantity(mallOrderItemDetail.getCheckQuantity());
                mallOrderItemDetail1.setExFactoryPrice(mallOrderItemDetail.getExFactoryPrice());
                mallOrderItemDetail1.setRate(mallOrderItemDetail.getRate());
                mallOrderItemDetail1.setUpdateTime(new Date());
                mallOrderItemDetail1.setTotalPrice(mallOrderItemDetail1.getCheckQuantity().multiply(mallOrderItemDetail1.getCurrentUnitPrice()));
                mallOrderItemDetail1.setResidualQuantity(mallOrderItemDetail1.getCheckQuantity());
                mallOrderItemDetailMapper.updateByPrimaryKey(mallOrderItemDetail1);
                total_price = total_price.add(mallOrderItemDetail1.getTotalPrice());
                quantity = quantity.add(mallOrderItemDetail1.getCheckQuantity());
            } else {
                mallOrderItemDetail.setOrderItemDetailId(null);
                mallOrderItemDetail.setOrderItemId(item_id);
                mallOrderItemDetail.setCreateTime(new Date());
                mallOrderItemDetail.setUpdateTime(new Date());
                mallOrderItemDetail.setTotalPrice(mallOrderItemDetail.getCheckQuantity().multiply(mallOrderItemDetail.getCurrentUnitPrice()));
                mallOrderItemDetail.setResidualQuantity(mallOrderItemDetail.getCheckQuantity());
                mallOrderItemDetailMapper.insert(mallOrderItemDetail);
                total_price = total_price.add(mallOrderItemDetail.getTotalPrice());
                quantity = quantity.add(mallOrderItemDetail.getCheckQuantity());
            }
        }
        if (quantity.compareTo(new BigDecimal(0)) == 0) {
            current_unit_price = new BigDecimal(0);
        } else {
            current_unit_price = total_price.divide(quantity);
        }
        MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(item_id);
        MallOrder mallOrder = mallOrderMapper.selectByOrderNo(mallOrderItem.getOrderNo());
        mallOrder.setPayment(mallOrder.getPayment().subtract(mallOrderItem.getTotalPrice()).add(total_price));
        mallOrderMapper.updateByPrimaryKey(mallOrder);
        mallOrderItem.setCurrentUnitPrice(current_unit_price);
        mallOrderItem.setTotalPrice(total_price);
        mallOrderItem.setQuantity(quantity);
        mallOrderItem.setResidualQuantity(quantity);
        mallOrderItemMapper.updateByPrimaryKey(mallOrderItem);
        return ServerResponse.createBySuccess();
    }

    @AuthRequired
    @DeleteMapping("deleteOrderItemDetail")
    @ApiOperation(value = "删除产品物料编码")
    public ServerResponse<String> deleteOrderItemDetail(Integer orderItemDetailId) {
        if (orderItemDetailId == null) {
            return ServerResponse.createBySuccess("本地删除");
        }
        MallOrderItemDetail mallOrderItemDetail = mallOrderItemDetailMapper.selectByPrimaryKey(orderItemDetailId);
        MallOrderItem mallOrderItem = mallOrderItemMapper.selectByPrimaryKey(mallOrderItemDetail.getOrderItemId());
        MallOrder mallOrder = mallOrderMapper.selectByOrderNo(mallOrderItem.getOrderNo());
        mallOrderItem.setTotalPrice(mallOrderItem.getTotalPrice().subtract(mallOrderItemDetail.getCurrentUnitPrice().multiply(mallOrderItemDetail.getCheckQuantity())));
        mallOrderItem.setQuantity(mallOrderItem.getQuantity().subtract(mallOrderItemDetail.getCheckQuantity()));
        mallOrderItem.setResidualQuantity(mallOrderItem.getQuantity());
        if (mallOrderItem.getQuantity().compareTo(new BigDecimal(0)) == 0) {
            mallOrderItem.setCurrentUnitPrice(new BigDecimal(0));
        } else {
            mallOrderItem.setCurrentUnitPrice(mallOrderItem.getTotalPrice().divide(mallOrderItem.getQuantity()));
        }
        mallOrder.setPayment(mallOrder.getPayment().subtract(mallOrderItemDetail.getCurrentUnitPrice().multiply(mallOrderItemDetail.getCheckQuantity())));
        mallOrderItemDetailMapper.deleteByPrimaryKey(orderItemDetailId);
        mallOrderItemMapper.updateByPrimaryKey(mallOrderItem);
        mallOrderMapper.updateByPrimaryKey(mallOrder);
        return ServerResponse.createBySuccess("删除成功");
    }

    @PostMapping("updateProduct")
    @ApiOperation(value = "更新产品表")
    public ServerResponse<List> updateProduct(MultipartFile file,
                                              HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);


        List list = ReadExcel.readExcel(tempFile);
        assert list != null;
        list.remove(0);
        list.remove(0);
//        list.remove(0);
//        list.remove(0);
//        list.remove(0);
        list.remove(list.size() - 1);


        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            //如果数据残缺跳过
//            if (taskList.get(4) == null || taskList.get(4).equals("")
//                    || taskList.get(8) == null || taskList.get(8).equals("")
//                    || taskList.get(9) == null || taskList.get(9).equals("")
//                    || taskList.get(10) == null || taskList.get(10).equals("")
//                    ) {
//                continue;
//            }
            String category;
            String fineness;
            String gloss;
            String section;
            String pore_number;
            String single_share;
            String model;
            String color;
            String network;
            String twisting = taskList.get(7);
            if (twisting.equals("S") || twisting.equals("Z")) {
                twisting = twisting + "捻";
            } else {
                twisting = "无捻向";
            }
            MallProduct mallProduct1 = mallProductMapper.selectByModelAndTwisting(taskList.get(5), twisting);
            if (mallProduct1 == null) {
                //如果没有product，创建产品
                MallProduct mallProduct2 = new MallProduct();
                //获取物料名称里的数据
                String[] s = iProductService.AnalysisMaterialName(taskList.get(3));
                category = s[0];
                gloss = s[1];
                section = s[2];
                color = taskList.get(8);
                //获取规格里的数据
                String s1 = taskList.get(4);
                if (s1.contains("*")) {
                    s1 = s1.substring(0, s1.indexOf("*"));
                }
                fineness = s1.substring(0, s1.indexOf("/"));
                pore_number = s1.substring(s1.indexOf("/") + 1, s1.length());
                //型号
                model = taskList.get(5);
                //获取网络合股里的数据
                String[] s2 = iProductService.AnalysisNetworkPly(taskList.get(12));
                single_share = s2[0];
                network = s2[1];

                //设置category_id
                Integer count1 = mallAttrValueMapper.checkCategory(category);
                method1(category, count1);
                Integer category_id = mallAttrValueMapper.selectByQuery(category, 6);
                mallProduct2.setCategoryId(category_id);

                //设置name
                String name = category + "," + gloss + "," + model + "," + fineness + ",/" + pore_number + "," + single_share
                        + "," + color + "," + section + "," + network + "," + twisting + ",";
                mallProduct2.setName(name);

                //设置subtitle
                mallProduct2.setSubtitle(s[4]);
                //设置图片
                mallProduct2.setMainImage(s[5]);
                //设置默认参数
                mallProduct2.setPrice(new BigDecimal(20));
                mallProduct2.setStock(30000);
                mallProduct2.setStatus(1);
                mallProduct2.setCreateTime(new Date());
                mallProduct2.setIsnew(0);
                mallProduct2.setShopId(1);
                //设置content
                mallProduct2.setContent(s[6]);
                //设置title
                mallProduct2.setTitle(category + " " + fineness + "dtex/" + pore_number + "f " + gloss);
                mallProductMapper.insert(mallProduct2);

                //获得product_id
                Integer product_id = mallProductMapper.findByProductName(name);

                //创建attr_connect表数据
                MallAttrConnect mallAttrConnect = new MallAttrConnect();
                mallAttrConnect.setProductId(product_id);
                //创建category connnect
                Integer count2 = mallAttrValueMapper.checkCategory(category);
                method1(category, count2);
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(category, 6));
                mallAttrConnect.setAttrValue(category);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建fineness connnect
                Integer count3 = mallAttrValueMapper.checkFineness(fineness);
                if (count3 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(3);
                    mallAttrValue.setValue(fineness);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(fineness, 3));
                mallAttrConnect.setAttrValue(fineness);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建gloss connnect
                Integer count4 = mallAttrValueMapper.checkGloss(gloss);
                if (count4 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(1);
                    mallAttrValue.setValue(gloss);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(gloss, 1));
                mallAttrConnect.setAttrValue(gloss);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建section connnect
                Integer count5 = mallAttrValueMapper.checkSection(section);
                if (count5 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(2);
                    mallAttrValue.setValue(section);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(section, 2));
                mallAttrConnect.setAttrValue(section);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建pore_number connnect
                Integer count6 = mallAttrValueMapper.checkPore_numberId(pore_number);
                if (count6 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(4);
                    mallAttrValue.setValue(pore_number);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(pore_number, 4));
                mallAttrConnect.setAttrValue(pore_number);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建single_share connnect
                Integer count7 = mallAttrValueMapper.checkSingle_shareId(single_share);
                if (count7 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(5);
                    mallAttrValue.setValue(single_share);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(single_share, 5));
                mallAttrConnect.setAttrValue(single_share);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建model connnect
                Integer count8 = mallAttrValueMapper.checkModel(model);
                if (count8 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(7);
                    mallAttrValue.setValue(model);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(model, 7));
                mallAttrConnect.setAttrValue(model);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建color connnect
                Integer count9 = mallAttrValueMapper.checkColor(color);
                if (count9 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(9);
                    mallAttrValue.setValue(color);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(color, 9));
                mallAttrConnect.setAttrValue(color);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建network connnect
                Integer count10 = mallAttrValueMapper.checkNetwork(network);
                if (count10 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(65);
                    mallAttrValue.setValue(network);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(network, 65));
                mallAttrConnect.setAttrValue(network);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建twisting connnect
                Integer count11 = mallAttrValueMapper.checkTwisting(twisting);
                if (count11 == 0) {
                    MallAttrValue mallAttrValue = new MallAttrValue();
                    mallAttrValue.setParentId(64);
                    mallAttrValue.setValue(twisting);
                    mallAttrValue.setSeque(0);
                    mallAttrValueMapper.insert(mallAttrValue);
                }
                mallAttrConnect.setAttrId(mallAttrValueMapper.selectByQuery(twisting, 64));
                mallAttrConnect.setAttrValue(twisting);
                mallAttrConnectMapper.insert(mallAttrConnect);

                //创建价格
                MallPrice mallPrice = new MallPrice();
                mallPrice.setProductId(product_id);
                mallPrice.setPriceStart(0);
                mallPrice.setPriceEnd(999999);
                mallPrice.setPriceNum(new BigDecimal(20));
                mallPrice.setGrade(taskList.get(6));
                mallPriceMapper.insert(mallPrice);

                //初始化mall_hot表
                MallHot mallHot = new MallHot();
                mallHot.setUpdateTime(new Date());
                mallHot.setStatus(1);
                mallHot.setProductId(product_id);
                mallHot.setSalesVolume(new BigDecimal(0));
                mallHot.setRank(0);
                mallHotMapper.insert(mallHot);
            } else {
                MallPrice mallPrice = mallPriceMapper.selectByIdAndGrade(mallProduct1.getId(), taskList.get(6));
                if (mallPrice == null) {
                    //如果价格不存在
                    MallPrice mallPrice1 = new MallPrice();
                    mallPrice1.setProductId(mallProduct1.getId());
                    mallPrice1.setGrade(taskList.get(6));
                    mallPrice1.setPriceNum(new BigDecimal(20));
                    mallPrice1.setPriceStart(0);
                    mallPrice1.setPriceEnd(999999);
                    mallPriceMapper.insert(mallPrice1);
                }
            }
        }

        return ServerResponse.createBySuccess(list);
    }

    private void method1(String category, Integer count1) {
        if (count1 == 0) {
            MallAttrValue mallAttrValue = new MallAttrValue();
            mallAttrValue.setParentId(6);
            mallAttrValue.setValue(category);
            mallAttrValue.setSeque(0);
            mallAttrValueMapper.insert(mallAttrValue);
        }
    }

    @AuthRequired
    @PostMapping("updateProductByCondition")
    @ApiOperation(value = "按条件修改产品")
    public ServerResponse<String> updateProductByCondition(@RequestBody ConditionVo conditionVo) {
        if (!conditionVo.getMain_image().equals("[]")) {
            conditionVo.setMain_image(conditionVo.getMain_image().substring(0, conditionVo.getMain_image().length() - 1));
        } else {
            conditionVo.setMain_image(null);
        }
        mallProductMapper.updateByCondition(conditionVo.getSubtitle(), conditionVo.getMain_image(), conditionVo.getContent(), conditionVo.getModel(), conditionVo.getCategory(), conditionVo.getGloss());
        return ServerResponse.createBySuccess("修改成功");
    }

    @PostMapping("updateOut")
    @ApiOperation(value = "更新出库表")
    public ServerResponse<String> updateOut(MultipartFile file,
                                            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        File tempFile;

        tempFile = getFile(file, request, null);

        List list = ReadExcel.readExcel(tempFile);

        assert list != null;
        list.remove(0);
        list.remove(0);
        list.remove(list.size() - 1);

        for (Object aList : list) {
            List<String> taskList = (ArrayList<String>) aList;
            NcOutStock ncOutStock = new NcOutStock();
            ncOutStock.setSalesman(taskList.get(0));
            ncOutStock.setSalesType(taskList.get(1));
            ncOutStock.setBusName(taskList.get(2));
            ncOutStock.setSalesOrderNo(taskList.get(3));
            ncOutStock.setOutStockDate(taskList.get(4));
            ncOutStock.setOutNo(taskList.get(5));
            ncOutStock.setInventoryOrganization(taskList.get(6));
            ncOutStock.setContractNo(taskList.get(7));
            ncOutStock.setCarNo(taskList.get(8));
            ncOutStock.setGrossWeight(taskList.get(9));
            ncOutStock.setHeaderRemark(taskList.get(10));
            ncOutStock.setSequence(taskList.get(11));
            ncOutStock.setMaterialCode(taskList.get(12));
            ncOutStock.setMaterialName(taskList.get(13));
            ncOutStock.setManualNo(taskList.get(14));
            ncOutStock.setSortName(taskList.get(15));
            ncOutStock.setSpecifications(taskList.get(16));
            ncOutStock.setModel(taskList.get(17));
            ncOutStock.setFactory(taskList.get(18));
            ncOutStock.setGrade(taskList.get(19));
            ncOutStock.setTiwsting(taskList.get(20));
            ncOutStock.setWeight(taskList.get(21));
            ncOutStock.setBox(taskList.get(22));
            ncOutStock.setTheOriginalCurrencyUnitPrice(taskList.get(23));
            ncOutStock.setTotalPriceOfOriginalCoin(taskList.get(24));
            ncOutStock.setCurrencyUnitPrice(taskList.get(25));
            ncOutStock.setTotalLocalCurrencyPriceAndTax(taskList.get(26));
            ncOutStock.setNoTaxAmount(taskList.get(27));
            ncOutStock.setTax(taskList.get(28));
            ncOutStock.setFreight(taskList.get(29));
            ncOutStock.setQuotation(taskList.get(30));
            ncOutStockMapper.insert(ncOutStock);
        }
        return ServerResponse.createBySuccess("导入成功");
    }

    @GetMapping("update2")
    @ApiOperation(value = "更新")
    public ServerResponse update2() {
        List<MallProduct> list = mallProductMapper.selectAll();
        for (MallProduct mallProduct : list) {
            mallProduct.setTitle(mallProduct.getTitle().replaceAll("×", "*"));
            mallProductMapper.updateByPrimaryKey(mallProduct);
        }
        return ServerResponse.createBySuccess();
    }

    @GetMapping("test222")
    @ApiOperation(value = "111")
    public ServerResponse<String> test222() {
        Map<String, String> map = new HashMap<>();
        String a = "0";
        map.put("order_status", a);
        String s = HttpClientUtil.doGetWithParam("http://localhost:8080/api/order/list2", map);
        return ServerResponse.createBySuccess(s);
    }

}
